package cn.cfg;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.List;
import java.util.Properties;

public class ConfigParser {
    // 检查 Property 是否符合规范 至少包含 name 及 value
    private static void checkFiled(Element e) throws DocumentException {
        if (e.elementText("name") == null || e.elementText("name").isEmpty()) {
            throw new DocumentException("config: There is an unnamed 'property' node present ");
        }
        if (e.elementText("value") == null || e.elementText("value").isEmpty()) {
            throw new DocumentException("config: [" + e.elementText("name") + "] Missing attribute 'value' ");
        }
    }
    // 获取 XML配置项 解析得到的 Config 类
    public static Configs parse(String path) throws DocumentException {
        Properties properties = new Properties();
        SAXReader reader = new SAXReader();

        Document document = reader.read(new File(path));
        Element root = document.getRootElement();
        List<Element> elements = root.elements("property"); // 仅识别标识为 property 的节点内容
        // 遍历获取 Property节点 并储存至 Properties 对象内
        for (Element e : elements) {
            checkFiled(e);
            properties.setProperty(e.elementText("name"), e.elementText("value"));
        }
        // 返回解析后的 Configs 对象
        return new Configs(properties);
    }

}
